<template>
	<view class="app">
		<AppNavbar :bgColor="'#ffff'" leftIconColor="black"
			:title="type == 'drinking'?  'Drinking water setting':'Feeding setting'" titlecolor="black"
			:fontWeight="600" righticon="/static/icon/bingou@2x.png" @rightClick="feedSave"></AppNavbar>
		<!-- 滑动标签 -->
		<up-tabs @click="changetab" itemStyle="width:50%;height:80rpx" :list="list1" lineColor='#f9a438' lineWidth='30'
			:activeStyle="{
            color: '#f9a438',
            fontWeight: 'bold',
            fontSize:'28rpx'
        }" :inactiveStyle="{
            color: '#a79fa2',
            fontSize:'28rpx'
        }"></up-tabs>

		<!-- 日历组件 -->
		<calendar ref="calendarRef" v-if="state.tabkey" @changeTime="datechange" @changeMonth="getMonth"></calendar>

		<!-- 饲养阶段 -->
		<view class="Feeding-stages p-2">
			<p class="my-2 font-weight-600">{{type == 'drinking'? 'Drinking':'Feeding'}} stage</p>
			<view class="Feeding-stages-box d-flex">

				<view @click="state.findkey = index"
					class="Feeding-stage-item bor-radius-10 m-1 ml-0 font-weight-600 t-center"
					v-for="(item,index) in state.planlist"
					:style="{'background':state.dietaryProgramType?'linear-gradient(0deg, #3ec1de 1.29%, #5590e2 94.17%)':'linear-gradient(0deg, #ffbb2e 1.29%, #fe8609 94.17%)'}">
					{{item.time}}
					<image src="/static/icon/clone.png" mode="" @click="delplan(index)"></image>
				</view>
				<view class="Feeding-stage-item-add  bor-radius-10 m-1 font-weight-600 t-center"
					style="color: #9A9A9A ;background:none;background-color: #fff;" @click="append">
					append
				</view>
			</view>
		</view>
		<!-- 喂食量 -->
		<view class="Feeding-amount p-2">
			<p class="my-2 font-weight-600" style="margin-bottom: 120rpx;">
				{{type == 'drinking'? 'Water intake':'Feeding amount'}}
			</p>
			<view class="Feeding-amount-box mx-auto p-1" @touchend="mousedown">
				<view class="Feeding-amount-box-active origin t-center" :class="{'blur':type == 'drinking'}"
					:style="{'height':state.fedAmount+'px'}">
					<text class="pb-2 font-weight-600">{{type == 'drinking'? 'Water intake':'Feeding amount'}}</text>
				</view>
			</view>
			<view class="Feeding-amount-detail bor-radius-10 mx-auto my-2 t-center">
				<p class="f-size-14 font-weight-600 my-1">
					{{state.fedAmount < 0?9:(state.fedAmount*4).toFixed(0)}}{{type == 'drinking'? 'ml':'g'}}
				</p>
				<p class="f-size-12 font-weight-600">day</p>
			</view>
		</view>




		<up-datetime-picker :show="state.show" v-model="state.timevalue" mode="time" format="HH:mm"
			@confirm="tiemconfirm"></up-datetime-picker>
	</view>
</template>

<script setup>
	import calendar from '@/components/calendar/calendar.vue'
	import {
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		DietplanSave,
		getdietplan,
		getdietplanMonth
	} from '../../api/Dietplan';

	let calendarRef = ref()

	// 创建响应式数据  
	const list1 = reactive([{
			name: 'everyday'
		},
		{
			name: 'Custom'
		}
	]);
	let state = reactive({
		show: false,
		timevalue: '',
		fedAmount: 0,
		planlist: [],
		findkey: 0,
		dietaryProgramId: '',
		tabkey: 0,
		dietaryProgramType: 0,
		dietaryProgramDate: '',
		Monthdiedata: {}, //月份饮食数据
		scrollTop: 0,
		chokerId: ''
	})
	let type = ref('')
	onLoad((e) => {
		if (e.type == 'drinking') {
			state.dietaryProgramType = 1
		}
		state.chokerId = e.chokerId
		type.value = e.type
		init()
		initDate()
	})

	watch(() => state.findkey, (newValue, oldValue) => {
		let list = state.planlist
		state.fedAmount = list[state.findkey].amountPlan.substring(0, list[state.findkey]
			.amountPlan
			.length - 1) / 4
	}, {
		deep: true
	})

	const append = () => {

		console.log(state.planlist[state.planlist.length - 1], state.planlist.length);

		if (state.planlist[state.planlist.length - 1]?.amountPlan || !state.planlist.length) {
			state.show = true
		} else {
			uni.tools.showTips('请先将上一个饲养阶段保存')
		}
	}

	const initDate = () => {
		const currentDate = new Date();
		const currentYear = currentDate.getFullYear();
		const currentMonth = currentDate.getMonth() + 1;
		const currentDay = currentDate.getDate();

		// 使用padStart确保月份和日期始终是两位数
		const formattedMonth = String(currentMonth).padStart(2, '0');
		const formattedDay = String(currentDay).padStart(2, '0');

		state.dietaryProgramDate = `${currentYear}-${formattedMonth}-${formattedDay}`;
	}

	const init = async () => { //获取当日的饮食
		let params = {
			chokerId: state.chokerId,
			dietaryProgramType: state.dietaryProgramType,
			type: 1
		}
		let res = await getdietplan(params)
		state.planlist = res.data || []
		if (res.data.length) {
			let CroppingNum = state.dietaryProgramType ? 2 : 1
			state.fedAmount = res.data[state.findkey].amountPlan.substring(0, res.data[state.findkey].amountPlan
				.length - CroppingNum) / 4
		}
		console.log(res.msg);
		if (res.msg.length > 9) {
			state.dietaryProgramId = res.msg
		}
	}


	const getMonthdietData = async (Month) => { //获取每个月的饮食
		let year = new Date().getFullYear()
		let params = {
			chokerId: state.chokerId,
			dietaryProgramType: state.dietaryProgramType,
			time: year + '-' + Month
		}
		let res = await getdietplanMonth(params)
		let list = []
		res.data.list.forEach(v => {
			const dateString = v.dietaryProgramDate
			const parts = dateString.split('-');
			const day = parts[2].split(' ')[0];
			list.push((parseInt(day, 10) - 1))
			state.Monthdiedata[day] = JSON.parse(v.dietaryJson)
			if (v.dietaryProgramId) {
				state.Monthdiedata[day][0].dietaryProgramId = v.dietaryProgramId
			}
		})
		calendarRef.value.modifyactivekey(list)

		let dietarylist = JSON.parse(res.data.list[0].dietaryJson)

		state.fedAmount = dietarylist[0].amountPlan.substring(0, dietarylist[0].amountPlan
			.length - 1) / 4
	}


	const tiemconfirm = (e) => {
		state.planlist.push({
			time: e.value
		})
		// console.log(e.value);
		state.show = false
		state.fedAmount = 0
	}

	const datechange = (val) => { //改变日期的时候触发
		console.log(val, state.Monthdiedata);
		state.dietaryProgramDate = val.all
		if (!state.Monthdiedata[val.day]) { //当点击的日没有数据会触发
			state.dietaryProgramId = ''
			state.planlist = []
			state.fedAmount = 0
		} else {
			state.dietaryProgramId = state.Monthdiedata[val.day][0].dietaryProgramId
			state.planlist = state.Monthdiedata[val.day]
			state.fedAmount = state.Monthdiedata[val.day][0].amountPlan.substring(0, dietarylist[0].amountPlan
				.length - 1) / 4
		}
	}

	const getMonth = (val) => { //选择月份的时候触发
		getMonthdietData(val)
	}


	const mousedown = (e) => {
		getElementBottomDistance('.Feeding-amount-box').then(distance => {
			state.fedAmount = distance - e.changedTouches[0].pageY - 10
		})
	}

	const feedSave = () => {
		let params = {
			chokerId: state.chokerId,
			dietaryProgramDate: state.dietaryProgramDate,
			dietaryProgramType: state.dietaryProgramType
		}

		params.dietaryJson = []
		state.planlist.forEach(v => {
			let amountPlan = v.amountPlan ? v.amountPlan : state.fedAmount * 4
			v.amountPlan = amountPlan
			if (!amountPlan.length) {
				amountPlan = amountPlan.toFixed(0) + (state
					.dietaryProgramType ?
					'ml' : 'g')
			}
			console.log(amountPlan, 'ad', amountPlan);
			params.dietaryJson.push({
				time: v.time,
				amountPlan: amountPlan
			})
		})

		params.dietaryJson = JSON.stringify(params.dietaryJson)
		if (state.dietaryProgramId) {
			params.dietaryProgramId = state.dietaryProgramId
		}

		console.log(params);

		DietplanSave(params).then(res => {
			uni.tools.showTips('保存成功')
		})
	}

	const changetab = (item) => {
		state.tabkey = item.index
		if (item.index) {
			const currentDate = new Date();
			const Month = currentDate.getMonth() + 1; //获得当前月份
			getMonthdietData(Month)
		}
	}
	//删除喂食时间点
	const delplan = (i) => {
		state.planlist.splice(i, 1)
	}



	onPageScroll((e) => { //监听页面滚动
		state.scrollTop = e.scrollTop
	})

	// 获取元素高度减去页面高度
	const getElementBottomDistance = (selector) => {
		return new Promise((resolve, reject) => {
			const query = uni.createSelectorQuery().in(this);
			query.select(selector).boundingClientRect(data => {
				if (data) {
					// 获取页面高度
					const bottomDistance = data.height + data.top + state.scrollTop
					resolve(bottomDistance);
				} else {
					reject(new Error('Element not found'));
				}
			}).exec();
		});
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f8f7fc;
	}

	.app {
		.Feeding-stages {

			.Feeding-stage-item,
			.Feeding-stage-item-add {
				width: 156rpx;
				height: 64rpx;
				line-height: 64rpx;
				background: $uni-bg-linear-origin;
				color: $uni-bg-color;
				position: relative;

				image {
					width: 24rpx;
					height: 24rpx;
					position: absolute;
					right: 5rpx;
				}
			}
		}

		.Feeding-amount {
			.Feeding-amount-box {
				overflow: hidden;
				box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.1);
				border-radius: 48rpx;
				width: 224rpx;
				height: 560rpx;
				background-color: $uni-bg-color;
				transform: rotate(180deg);

				.Feeding-amount-box-active {
					width: 100%;
					// height: 50%;
					border-radius: 48rpx;

					text {
						display: block;
						transform: rotate(180deg);
						color: $uni-bg-color;
						font-size: 23rpx;
					}
				}
			}

			.Feeding-amount-detail {
				width: 130rpx;
				height: 108rpx;
				background-color: $uni-bg-color;
				overflow: hidden;

				:last-child {
					color: $uni-grey;
				}
			}
		}
	}

	.origin {
		background: linear-gradient(0deg, #ffbb2e 1.29%, #fe8609 94.17%);
	}

	.blur {
		background: linear-gradient(0deg, rgba(62, 193, 222, 1) 1.29%, rgba(85, 144, 226, 1) 94.17%);
	}

	::v-deep .swiper {
		height: 330rpx !important;
	}
</style>